package org.yecq.tradedata.algorithm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.yecq.tradedata.bean.FuturesDayKLineBean;

/**
 * 期货简单移动平均线
 *
 * @author yecq
 */
@Component
@Scope("prototype")
class MovingAverageFutures {

    private int day_number;
    private String date;
    private String code;

    @Autowired
    private Utils utils;

    // 每次计算都保存一下历史价格，免得重复计算
    private double[] close_list;

    public MovingAverageFutures() {
        this.close_list = null;
    }

    public MovingAverageFutures(int day_number, String date, String code) {
        this.day_number = day_number;
        this.date = date;
        this.code = code;
        this.close_list = null;
    }

    public void setDay_number(int day_number) {
        this.day_number = day_number;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public double[] getClose_list() {
        return close_list;
    }

    // 获取价格数据
    private List<Double> getCloseList() {
        List<FuturesDayKLineBean> list = this.utils.getDayKLineList4Futures(this.code, this.date, this.day_number);
        if (list.size() < this.day_number) {
            throw new NotEnoughKLineException("没有这么多K线");
        }

        // 第一条应该是指定日期
        FuturesDayKLineBean first = list.get(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (!sdf.parse(first.getDate()).equals(sdf.parse(this.date))) {
                throw new NotEnoughKLineException("第一条记录不是" + this.date);
            }
        } catch (ParseException ex) {
            throw new IllegalStateException(ex.getMessage());
        }

        List<Double> ret = new ArrayList(list.size());
        for (FuturesDayKLineBean bean : list) {
            ret.add(bean.getClose());
        }

        return ret;
    }

    // 获取价格的数组
    double[] getCloseArray() {
        List<Double> list = getCloseList();
        double[] ret = new double[list.size()];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = list.get(i);
        }

        return ret;
    }

    public Double compute() {
        this.close_list = getCloseArray();
        if (close_list.length == 0) {
            return null;
        }
        double sum = 0.;
        for (double item : close_list) {
            sum += item;
        }

        return sum / this.day_number;
    }
}
